<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cookie-Based Authentication Demo</title>
    <style>
        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --success-color: #28a745;
            --danger-color: #dc3545;
            --warning-color: #FFC107;
            --border-radius: 10px;
            --transition: all 0.3s ease;
            --font-mono: 'SF Mono', Monaco, monospace;
            --box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            --box-shadow-hover: 0 10px 25px rgba(0,0,0,0.1);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--primary-gradient);
            min-height: 100vh;
            padding: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: var(--box-shadow);
            padding: 40px;
            max-width: 900px;
            width: 100%;
            position: relative;
            overflow: hidden;
            animation: slideIn 0.6s ease-out;
        }

        @keyframes slideIn {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.3; }
        }

        @keyframes checkIn {
            from { transform: scale(0) rotate(-180deg); opacity: 0; }
            to { transform: scale(1) rotate(0); opacity: 1; }
        }

        .container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--primary-gradient);
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
        }

        .auth-logo {
            font-size: 48px;
            margin-bottom: 20px;
        }

        h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 28px;
            font-weight: 700;
        }

        h2 {
            color: #333;
            margin-bottom: 15px;
            font-size: 20px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 16px;
        }

        .session-status {
            position: absolute;
            top: 20px;
            right: 20px;
            padding: 10px 20px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 8px;
            animation: statusPulse 2s infinite;
        }

        @keyframes statusPulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.8; }
        }

        .session-status.logged-out {
            background: rgba(220, 53, 69, 0.1);
            color: var(--danger-color);
            border: 1px solid rgba(220, 53, 69, 0.3);
        }

        .session-status.logged-in {
            background: rgba(40, 167, 69, 0.1);
            color: var(--success-color);
            border: 1px solid rgba(40, 167, 69, 0.3);
        }

        .session-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: currentColor;
            animation: blink 2s infinite;
        }

        .section {
            margin-bottom: 30px;
            padding: 25px;
            background: rgba(255, 255, 255, 0.7);
            border-radius: 15px;
            border: 1px solid rgba(255, 255, 255, 0.3);
            transition: var(--transition);
        }

        .section:hover {
            transform: translateY(-2px);
            box-shadow: var(--box-shadow-hover);
        }

        .section p {
            color: #666;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .user-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-bottom: 25px;
        }

        .user-card {
            background: rgba(255, 255, 255, 0.9);
            padding: 18px;
            border-radius: 12px;
            border: 2px solid rgba(255, 255, 255, 0.5);
            cursor: pointer;
            transition: var(--transition);
            position: relative;
            overflow: hidden;
        }

        .user-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(102, 126, 234, 0.1), transparent);
            transition: left 0.5s;
        }

        .user-card:hover::before {
            left: 100%;
        }

        .user-card:hover,
        .user-card.active {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
            border-color: #667eea;
            background: rgba(102, 126, 234, 0.05);
        }

        .user-card.active {
            background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.2);
        }

        .user-card.active::after {
            content: '✔';
            position: absolute;
            top: 10px;
            right: 10px;
            width: 24px;
            height: 24px;
            background: var(--primary-gradient);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            font-weight: bold;
            animation: checkIn 0.3s ease-out;
        }

        .user-card-icon {
            font-size: 28px;
            margin-bottom: 8px;
            text-align: center;
        }

        .user-card-name {
            font-weight: 600;
            color: #333;
            font-size: 15px;
            margin-bottom: 4px;
        }

        .user-card-credentials {
            font-family: var(--font-mono);
            font-size: 12px;
            color: #666;
            margin-bottom: 6px;
        }

        .user-card-password {
            font-size: 11px;
            color: #888;
            font-style: italic;
        }

        .role-badge {
            display: inline-block;
            background: #667eea;
            color: white;
            padding: 3px 10px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-top: 8px;
        }

        .role-badge.admin {
            background: linear-gradient(135deg, #dc3545, #c82333);
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
            font-size: 14px;
        }

        input[type="text"],
        input[type="password"] {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e1e5e9;
            border-radius: var(--border-radius);
            font-size: 16px;
            transition: var(--transition);
            background: white;
        }

        input[type="text"]:focus,
        input[type="password"]:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .input-wrapper {
            position: relative;
        }

        .input-icon {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #999;
            font-size: 18px;
        }

        .btn {
            display: inline-flex;
            align-items: center;
            gap: 8px;
            padding: 12px 24px;
            border: none;
            border-radius: var(--border-radius);
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            text-decoration: none;
            margin-right: 10px;
            margin-bottom: 10px;
            position: relative;
            overflow: hidden;
            color: white;
        }

        .btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
            transition: left 0.5s;
        }

        .btn:hover::before {
            left: 100%;
        }

        .btn:hover {
            transform: translateY(-2px);
        }

        .btn-primary {
            background: var(--primary-gradient);
        }

        .btn-primary:hover {
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .btn-success {
            background: linear-gradient(135deg, #4CAF50, #45a049);
        }

        .btn-success:hover {
            box-shadow: 0 10px 20px rgba(76, 175, 80, 0.3);
        }

        .btn-warning {
            background: linear-gradient(135deg, var(--warning-color), #ff9800);
        }

        .btn-warning:hover {
            box-shadow: 0 10px 20px rgba(255, 193, 7, 0.3);
        }

        .btn-clear {
            background: linear-gradient(135deg, #666, #555);
        }

        .btn-clear:hover {
            box-shadow: 0 10px 20px rgba(102, 102, 102, 0.3);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none !important;
        }

        .response {
            margin-top: 20px;
            padding: 20px;
            border-radius: var(--border-radius);
            white-space: pre-wrap;
            font-family: var(--font-mono);
            font-size: 14px;
            line-height: 1.5;
            display: none;
            transition: var(--transition);
            position: relative;
        }

        .response.show {
            display: block;
            animation: fadeIn 0.5s ease;
        }

        .response.success {
            background: rgba(40, 167, 69, 0.1);
            border: 1px solid rgba(40, 167, 69, 0.3);
            color: #155724;
        }

        .response.error {
            background: rgba(220, 53, 69, 0.1);
            border: 1px solid rgba(220, 53, 69, 0.3);
            color: #721c24;
        }

        .response-header {
            position: absolute;
            top: -10px;
            left: 20px;
            background: white;
            padding: 0 10px;
            font-size: 12px;
            font-weight: bold;
            color: inherit;
        }

        .loading {
            display: none;
            text-align: center;
            margin: 20px 0;
        }

        .loading.show {
            display: block;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        .transaction-details {
            display: none;
            margin-top: 20px;
        }

        .transaction-details.visible {
            display: block;
            animation: fadeIn 0.5s ease-out;
        }

        .http-message {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: var(--border-radius);
            margin-bottom: 15px;
            overflow: hidden;
        }

        .http-message-header {
            color: white;
            padding: 12px 20px;
            font-weight: 600;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .http-message-content {
            padding: 20px;
            font-family: var(--font-mono);
            font-size: 13px;
            line-height: 1.6;
            background: white;
        }

        .http-message-content pre {
            white-space: pre-wrap;
            word-wrap: break-word;
            word-break: break-all;
            overflow-wrap: break-word;
            margin: 0;
            font-family: inherit;
            font-size: inherit;
        }

        .http-request {
            border-left: 4px solid #007bff;
        }

        .http-request .http-message-header {
            background: linear-gradient(45deg, #007bff, #0056b3);
        }

        .http-response-200 {
            border-left: 4px solid var(--success-color);
        }

        .http-response-200 .http-message-header {
            background: linear-gradient(45deg, var(--success-color), #1e7e34);
        }

        .http-response-401 {
            border-left: 4px solid var(--warning-color);
        }

        .http-response-401 .http-message-header {
            background: linear-gradient(45deg, var(--warning-color), #e0a800);
        }

        .http-response-403 {
            border-left: 4px solid var(--danger-color);
        }

        .http-response-403 .http-message-header {
            background: linear-gradient(45deg, var(--danger-color), #c82333);
        }

        .http-method { color: #007bff; font-weight: bold; }
        .http-status-200 { color: var(--success-color); font-weight: bold; }
        .http-status-401 { color: var(--warning-color); font-weight: bold; }
        .http-status-403 { color: var(--danger-color); font-weight: bold; }
        .http-header-name { color: #6f42c1; font-weight: bold; }
        .http-header-value { color: #495057; }

        .transaction-flow {
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 20px 0;
            font-size: 24px;
            color: #6c757d;
        }

        .footer {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid rgba(255, 255, 255, 0.3);
            color: #666;
            font-size: 14px;
            text-align: center;
        }

        .cookie-info {
            background: rgba(102, 126, 234, 0.1);
            border: 1px solid rgba(102, 126, 234, 0.3);
            border-radius: var(--border-radius);
            padding: 15px;
            margin-top: 15px;
            font-size: 13px;
            color: #333;
        }

        .cookie-info-title {
            font-weight: 600;
            margin-bottom: 8px;
            color: #667eea;
        }

        .cookie-details {
            font-family: var(--font-mono);
            font-size: 12px;
            line-height: 1.5;
        }

        @media (max-width: 768px) {
            .container {
                padding: 20px;
                margin: 10px;
            }

            .section {
                padding: 20px;
            }

            .user-grid {
                grid-template-columns: 1fr;
            }

            .user-card {
                padding: 15px;
            }

            .user-card-icon {
                font-size: 24px;
            }

            .session-status {
                position: static;
                margin-bottom: 20px;
                justify-content: center;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="session-status logged-out" id="sessionStatus">
        <span class="session-indicator"></span>
        <span id="sessionText">Not Logged In</span>
    </div>

    <div class="header">
        <div class="auth-logo">🍪</div>
        <h1>Cookie-Based Authentication Demo</h1>
        <p class="subtitle">Test session-based authentication with cookies</p>
    </div>

    <div class="section">
        <h2>👥 User Selection</h2>
        <p>Click on any user card below to automatically fill in the credentials</p>
        <div class="user-grid" id="userGrid"></div>

        <div class="form-group">
            <label for="username">Username:</label>
            <div class="input-wrapper">
                <input type="text" id="username" placeholder="Enter username or click a user card above">
                <span class="input-icon">👤</span>
            </div>
        </div>
        <div class="form-group">
            <label for="password">Password:</label>
            <div class="input-wrapper">
                <input type="password" id="password" placeholder="Enter password or click a user card above">
                <span class="input-icon">🔒</span>
            </div>
        </div>
    </div>

    <div class="section">
        <h2>🔐 Login</h2>
        <p>Submit credentials to create a session and receive a session cookie</p>
        <button class="btn btn-primary" onclick="authAPI.login()">
            <span>🚀</span>
            Login
        </button>
        <div class="loading" id="loginLoading">
            <div class="spinner"></div>
            <div>Authenticating...</div>
        </div>
        <div id="loginResponse" class="response">
            <span class="response-header">Response</span>
        </div>
        <div class="cookie-info" id="cookieInfo" style="display: none;">
            <div class="cookie-info-title">🍪 Session Cookie Details</div>
            <div class="cookie-details" id="cookieDetails"></div>
        </div>
    </div>

    <div class="section">
        <h2>👤 Protected Profile</h2>
        <p>Access your profile using the session cookie (requires login)</p>
        <button class="btn btn-success" onclick="authAPI.fetchProfile()">
            <span>📋</span>
            Get My Profile
        </button>
        <div class="loading" id="profileLoading">
            <div class="spinner"></div>
            <div>Loading profile...</div>
        </div>
        <div id="profileResponse" class="response">
            <span class="response-header">Response</span>
        </div>
    </div>

    <div class="section">
        <h2>🚪 Logout</h2>
        <p>End your session and clear the session cookie</p>
        <button class="btn btn-warning" onclick="authAPI.logout()">
            <span>👋</span>
            Logout
        </button>
        <div class="loading" id="logoutLoading">
            <div class="spinner"></div>
            <div>Logging out...</div>
        </div>
        <div id="logoutResponse" class="response">
            <span class="response-header">Response</span>
        </div>
    </div>

    <div class="section">
        <h2>📊 HTTP Transaction Details</h2>
        <p>View detailed HTTP request and response messages</p>
        <button class="btn btn-clear" onclick="utils.clearTransactions()" style="margin-bottom: 15px;">
            <span>🗑️</span>
            Clear Transactions
        </button>
        <div id="transactionDetails" class="transaction-details">
            <p style="text-align: center; color: #6c757d; font-style: italic; padding: 20px;">
                Click any endpoint button to see detailed HTTP request/response messages
            </p>
        </div>
    </div>

    <div class="footer">
        <p>This demo showcases cookie-based session authentication</p>
    </div>
</div>

<script>
    // Configuration
    const CONFIG = {
        users: [
            { username: 'john', password: 'password123', name: 'John', icon: '👤', role: 'Regular User' },
            { username: 'jane', password: 'secret456', name: 'Jane', icon: '👤', role: 'Regular User' },
            { username: 'admin', password: 'admin123', name: 'Admin', icon: '👨‍💼', role: 'Administrator', isAdmin: true }
        ],
        endpoints: {
            login: '/login',
            profile: '/profile/me',
            logout: '/logout'
        }
    };

    // Session state management
    const sessionState = {
        isLoggedIn: false,
        username: null,
        sessionId: null
    };

    // Utility functions
    const utils = {
        getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
            return null;
        },

        showLoading(elementId, show) {
            const element = document.getElementById(elementId);
            element.classList.toggle('show', show);
        },

        displayResponse(elementId, response, isError = false) {
            const element = document.getElementById(elementId);
            const header = element.querySelector('.response-header');

            element.innerHTML = '';
            if (header) element.appendChild(header);
            element.appendChild(document.createTextNode(response));

            element.className = `response ${isError ? 'error' : 'success'} show`;
        },

        updateSessionStatus() {
            const statusElement = document.getElementById('sessionStatus');
            const statusText = document.getElementById('sessionText');

            if (sessionState.isLoggedIn) {
                statusElement.className = 'session-status logged-in';
                statusText.textContent = `Logged in as: ${sessionState.username}`;
            } else {
                statusElement.className = 'session-status logged-out';
                statusText.textContent = 'Not Logged In';
            }
        },

        updateCookieInfo(show = true) {
            const cookieInfo = document.getElementById('cookieInfo');
            const cookieDetails = document.getElementById('cookieDetails');

            if (show && sessionState.sessionId) {
                cookieInfo.style.display = 'block';
                cookieDetails.innerHTML = `
                    Name: session_id
                    Value: ${sessionState.sessionId || '(not accessible via JavaScript)'}
                `;
            } else {
                cookieInfo.style.display = 'none';
            }
        },

        clearTransactions() {
            const detailsContainer = document.getElementById('transactionDetails');
            detailsContainer.classList.remove('visible');
            setTimeout(() => {
                detailsContainer.innerHTML = `
                    <p style="text-align: center; color: #6c757d; font-style: italic; padding: 20px;">
                        Click any endpoint button to see detailed HTTP request/response messages
                    </p>
                `;
            }, 300);
        }
    };

    // HTTP Transaction handling
    const httpTransaction = {
        formatHeaders(headers) {
            return Object.entries(headers || {})
                .map(([name, value]) =>
                    `<span class="http-header-name">${name}:</span> <span class="http-header-value">${value}</span>`)
                .join('\n');
        },

        formatRequest(method, url, headers, body = null) {
            const urlObj = new URL(url, window.location.origin);
            let request = `<span class="http-method">${method}</span> ${urlObj.pathname}${urlObj.search} HTTP/1.1\n`;
            request += `<span class="http-header-name">Host:</span> <span class="http-header-value">${urlObj.host}</span>\n`;
            request += this.formatHeaders(headers);
            if (body) request += `\n${body}`;
            return request;
        },

        formatResponse(status, statusText, headers, body) {
            const statusClass = status === 200 ? 'http-status-200' :
                               status === 401 ? 'http-status-401' :
                               status === 403 ? 'http-status-403' : 'http-status-403';

            let formatted = `HTTP/1.1 <span class="${statusClass}">${status} ${statusText}</span>\n`;
            if (headers) formatted += this.formatHeaders(headers);
            if (body) formatted += `\n${body}`;
            return formatted;
        },

        display(transaction) {
            const detailsContainer = document.getElementById('transactionDetails');
            if (!detailsContainer) return;

            const responseClass = transaction.response.status === 200 ? 'http-response-200' :
                                 transaction.response.status === 401 ? 'http-response-401' :
                                 'http-response-403';

            detailsContainer.innerHTML = `
                <div class="http-message http-request">
                    <div class="http-message-header">🌐 HTTP Request</div>
                    <div class="http-message-content"><pre>${transaction.request}</pre></div>
                </div>
                <div class="transaction-flow">⬇️</div>
                <div class="http-message ${responseClass}">
                    <div class="http-message-header">📨 HTTP Response</div>
                    <div class="http-message-content"><pre>${transaction.responseText}</pre></div>
                </div>
            `;
            detailsContainer.classList.add('visible');
        },

        hide() {
            const detailsContainer = document.getElementById('transactionDetails');
            if (detailsContainer) {
                detailsContainer.classList.remove('visible');
                setTimeout(() => {
                    detailsContainer.innerHTML = '';
                }, 500);
            }
        }
    };

    // API functions
    const authAPI = {
        async makeRequest(url, options = {}, transactionOptions = {}) {
            const defaults = {
                credentials: 'include',
                headers: {}
            };
            const config = { ...defaults, ...options };

            try {
                const response = await fetch(url, config);
                const text = await response.text();

                // Build request headers for display
                const requestHeaders = { ...config.headers };
                if (transactionOptions.showCookie && document.cookie) {
                    requestHeaders['Cookie'] = document.cookie;
                }

                // Build response headers for display
                const responseHeaders = {
                    'Content-Type': response.headers.get('Content-Type') || 'text/plain',
                    'Content-Length': text.length
                };

                // Only show Set-Cookie for login and logout responses
                if (transactionOptions.showSetCookie) {
                    responseHeaders['Set-Cookie'] = document.cookie;
                }

                // Build transaction for display
                const transaction = {
                    request: httpTransaction.formatRequest(
                        config.method || 'GET',
                        url,
                        requestHeaders,
                        config.body
                    ),
                    response: {
                        status: response.status,
                        statusText: response.statusText
                    },
                    responseText: httpTransaction.formatResponse(
                        response.status,
                        response.statusText,
                        responseHeaders,
                        text
                    )
                };

                httpTransaction.display(transaction);

                return { response, text };
            } catch (error) {
                throw error;
            }
        },

        async login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            if (!username || !password) {
                utils.displayResponse('loginResponse', 'Please select a user or enter credentials', true);
                return;
            }

            utils.showLoading('loginLoading', true);

            try {
                const formData = new URLSearchParams({ username, password });
                const { response, text } = await this.makeRequest(CONFIG.endpoints.login, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body: formData.toString()
                }, {
                    showCookie: false,  // No cookie sent in login request
                    showSetCookie: true // Server sets cookie in response
                });

                if (response.ok) {
                    utils.displayResponse('loginResponse', `Status: ${response.status} ✅\n\n${text}`);

                    sessionState.isLoggedIn = true;
                    sessionState.username = username;
                    sessionState.sessionId = utils.getCookie('session_id');

                    utils.updateSessionStatus();
                    utils.updateCookieInfo();
                } else {
                    utils.displayResponse('loginResponse', `Error ${response.status} ❌\n\n${text}`, true);
                    Object.assign(sessionState, { isLoggedIn: false, username: null, sessionId: null });
                    utils.updateSessionStatus();
                    utils.updateCookieInfo(false);
                }
            } catch (error) {
                utils.displayResponse('loginResponse', `Network Error ❌\n\n${error.message}`, true);
            } finally {
                utils.showLoading('loginLoading', false);
            }
        },

        async fetchProfile() {
            utils.showLoading('profileLoading', true);

            try {
                const { response, text } = await this.makeRequest(CONFIG.endpoints.profile, {}, {
                    showCookie: true,    // Cookie sent with request
                    showSetCookie: false // No cookie set in response
                });

                if (response.ok) {
                    utils.displayResponse('profileResponse', `Status: ${response.status} ✅\n\n${text}`);
                } else {
                    utils.displayResponse('profileResponse', `Error ${response.status} ❌\n\n${text}`, true);

                    if (response.status === 401) {
                        Object.assign(sessionState, { isLoggedIn: false, username: null, sessionId: null });
                        utils.updateSessionStatus();
                    }
                }
            } catch (error) {
                utils.displayResponse('profileResponse', `Network Error ❌\n\n${error.message}`, true);
            } finally {
                utils.showLoading('profileLoading', false);
            }
        },

        async logout() {
            utils.showLoading('logoutLoading', true);

            try {
                const { response, text } = await this.makeRequest(CONFIG.endpoints.logout, {}, {
                    showCookie: true,   // Cookie sent with request
                    showSetCookie: true // Server clears cookie in response
                });

                if (response.ok) {
                    utils.displayResponse('logoutResponse', `Status: ${response.status} ✅\n\n${text}`);

                    Object.assign(sessionState, { isLoggedIn: false, username: null, sessionId: null });
                    utils.updateSessionStatus();
                    utils.updateCookieInfo(false);
                } else {
                    utils.displayResponse('logoutResponse', `Error ${response.status} ❌\n\n${text}`, true);
                }
            } catch (error) {
                utils.displayResponse('logoutResponse', `Network Error ❌\n\n${error.message}`, true);
            } finally {
                utils.showLoading('logoutLoading', false);
            }
        }
    };

    // UI Components
    const uiComponents = {
        createUserCard(user) {
            const card = document.createElement('div');
            card.className = 'user-card';
            card.dataset.username = user.username;
            card.dataset.password = user.password;

            card.innerHTML = `
                <div class="user-card-icon">${user.icon}</div>
                <div class="user-card-name">${user.name}</div>
                <div class="user-card-credentials">${user.username}</div>
                <div class="user-card-password">password: ${user.password}</div>
                <span class="role-badge ${user.isAdmin ? 'admin' : ''}">${user.role}</span>
            `;

            card.addEventListener('click', () => this.selectUser(card));
            return card;
        },

        selectUser(card) {
            document.querySelectorAll('.user-card').forEach(c => c.classList.remove('active'));
            card.classList.add('active');

            document.getElementById('username').value = card.dataset.username;
            document.getElementById('password').value = card.dataset.password;

            ['username', 'password'].forEach(id => {
                const input = document.getElementById(id);
                input.style.transition = 'none';
                input.style.background = 'linear-gradient(to right, rgba(102, 126, 234, 0.1), transparent)';
                setTimeout(() => {
                    input.style.transition = 'all 0.3s ease';
                    input.style.background = 'white';
                }, 100);
            });
        },

        updateActiveCard() {
            const username = document.getElementById('username').value;
            document.querySelectorAll('.user-card').forEach(card => {
                card.classList.toggle('active', card.dataset.username === username);
            });
        }
    };

    // Initialization
    async function checkSession() {
        const sessionId = utils.getCookie('session_id');
        if (!sessionId) {
            Object.assign(sessionState, { isLoggedIn: false, username: null, sessionId: null });
            utils.updateSessionStatus();
            return;
        }

        try {
            const response = await fetch(CONFIG.endpoints.profile, {
                method: 'GET',
                credentials: 'include'
            });

            if (response.ok) {
                const text = await response.text();
                const match = text.match(/Welcome (\w+)!/);
                if (match) {
                    Object.assign(sessionState, {
                        isLoggedIn: true,
                        username: match[1],
                        sessionId: sessionId
                    });
                    utils.updateCookieInfo();
                    uiComponents.updateActiveCard();
                }
            } else {
                Object.assign(sessionState, { isLoggedIn: false, username: null, sessionId: null });
            }
        } catch (error) {
            console.error('Session check failed:', error);
            Object.assign(sessionState, { isLoggedIn: false, username: null, sessionId: null });
        }

        utils.updateSessionStatus();
    }

    // Event listeners
    document.addEventListener('DOMContentLoaded', async () => {
        // Create user cards
        const userGrid = document.getElementById('userGrid');
        CONFIG.users.forEach(user => {
            userGrid.appendChild(uiComponents.createUserCard(user));
        });

        // Check existing session
        await checkSession();

        // Select first user if not logged in
        if (!sessionState.isLoggedIn) {
            const firstCard = document.querySelector('.user-card');
            if (firstCard) firstCard.click();
        }

        // Input field listeners
        ['username', 'password'].forEach(id => {
            document.getElementById(id).addEventListener('input', () => uiComponents.updateActiveCard());
        });

        // Enter key support
        ['username', 'password'].forEach(id => {
            document.getElementById(id).addEventListener('keypress', e => {
                if (e.key === 'Enter') authAPI.login();
            });
        });
    });
</script>
</body>
</html>
